package com.donger.upms.biz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.donger.common.core.constant.CommonConstants;
import com.donger.common.core.constant.SecurityConstants;
import com.donger.common.core.exception.BizException;
import com.donger.upms.api.entity.SysUser;
import com.donger.upms.api.service.ISysUserService;
import com.donger.upms.api.service.MobileService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@AllArgsConstructor
@Slf4j
public class MobileServiceImpl implements MobileService {

    private final RedisTemplate redisTemplate;
    private final ISysUserService sysUserService;

    @Override
    public Boolean sendSmsCode(String mobile) {

        List<SysUser> userList = sysUserService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhone, mobile));
        if (CollUtil.isEmpty(userList)) {
            log.error("手机号未注册: {}", mobile);
            throw new BizException("手机号未注册");
        }

        Object codeObj = redisTemplate.opsForValue().get(CommonConstants.DEFAULT_PHONE_KEY + mobile);

        if (codeObj != null) {
            log.error("手机号验证码未过期: {},{}", mobile, codeObj);

            throw new BizException("验证码发送频繁");
        }

        String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
        log.debug("手机号生成验证码成功:{},{}", mobile, code);

        redisTemplate.opsForValue().set(
                CommonConstants.DEFAULT_PHONE_KEY + mobile
                , code, SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
        return Boolean.TRUE;
    }
}
